﻿/************************************************************************************
 * xujiajun@yoozoo.com 御剑
 * 实现了LOD控制策略监听器的层级容器，使用LOD参数的变化来打开关闭层级
 ***********************************************************************************/

using WorldMapBase.Layer;
using WorldMapBase.LOD;

namespace WorldMapBase
{
    /// <summary>
    /// 实现了LOD控制策略监听器的层级容器，使用LOD参数的变化来打开关闭层级
    /// </summary>
    public class LODLayerContainer : LayerContainer, ILODListener
    {
        /// <summary>
        /// 用于将LOD变化百分比推送给层级的接口
        /// </summary>
        public interface ILODPercentListener
        {
            /// <summary>
            /// 更新LOD百分比
            /// </summary>
            /// <param name="lodLevel">LOD等级</param>
            /// <param name="percent">百分比数值范围为0-99</param>
            void OnUpdateLODPercent(int lodLevel, float percent);
        }

        /// <summary>
        /// 当前帧LOD等级
        /// </summary>
        protected int m_LodLevel;
        /// <summary>
        /// 当前帧LOD百分比
        /// </summary>
        protected float m_NextLevelPercent;
        /// <summary>
        /// 是否需要刷新百分比
        /// </summary>
        protected bool b_RefreshPercent;

        public void OnLODLevelChange(int currentLodLevel, int lastLodLevel)
        {
            LODLevelChange(currentLodLevel, lastLodLevel);
        }

        protected virtual void LODLevelChange(int currentLodLevel, int lastLodLevel)
        {
            // 隐藏之前LOD的层级
            DisableLayer(lastLodLevel);
            // 激活当前LOD的层级
            EnableLayer(currentLodLevel);
        }
        

        public void OnNextLODPercentUpdate(int lodLevel, float nextLevelPercent)
        {
            NextLODPercentUpdate(lodLevel, nextLevelPercent);
        }

        protected virtual void NextLODPercentUpdate(int lodLevel, float nextLevelPercent)
        {
            m_LodLevel = lodLevel;
            m_NextLevelPercent = nextLevelPercent;
            b_RefreshPercent = true;
        }

        public virtual int GetLodLevel(int level)
        {
            return m_LodLevel;
        }

        protected override void OnUpdate()
        {
            // 在这个地方更新LOD百分比是为了保证执行顺序。先更新视图，再更新百分比
            if (b_RefreshPercent)
            {
                // 更新层级的LOD百分比
                var layer = GetLayer(m_LodLevel) as ILODPercentListener;
                layer?.OnUpdateLODPercent(m_LodLevel, m_NextLevelPercent);

                b_RefreshPercent = false;
            }
        }
    }

}

